package com.ncmem.up6.database;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.JsonArray;
import com.ncmem.up6.database.mysql.MySQLFolder;
import com.ncmem.up6.database.odbc.OdbcFolder;
import com.ncmem.up6.database.oracle.OracleFolder;
import com.ncmem.up6.sql.*;
import com.ncmem.up6.utils.ConfigReader;
import com.ncmem.up6.utils.DataBaseType;
import com.ncmem.up6.utils.PathTool;
import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.ncmem.up6.model.FileInf;

public class DbFolder 
{
	public static DbFolder build(){

        if( ConfigReader.dbType() == DataBaseType.SqlServer ) return new DbFolder();
        else if( ConfigReader.dbType() == DataBaseType.MySQL ) return new MySQLFolder();
        else if( ConfigReader.dbType() == DataBaseType.Oracle ||
                ConfigReader.dbType() == DataBaseType.DMDB ) return new OracleFolder();
        else if( ConfigReader.dbType() == DataBaseType.KingBase ) return new OdbcFolder();
        else if( ConfigReader.dbType() == DataBaseType.MongoDB ) return new DbFolderMongodb();
        else return new DbFolder();
    }

	public DbFolder() 
	{
	}

    /**
     * 构建路径
     * @param fdCur
     * @return
     */
    public JSONArray build_path(JSONObject fdCur) {

        String id = fdCur.getString("id").trim();
        String pid = fdCur.getString("pid").trim();
        String pathRel = fdCur.getString("pathRel").trim();
        List<FileInf> rels = new ArrayList<FileInf>();

        //根目录
        if (pathRel=="/")
        {
            FileInf f = new FileInf();
            f.pathSvr = "/";
            f.nameLoc = "根目录";
            rels.add(f);

            FileInf dir = new FileInf();
            dir.pathRel = pathRel;
            int rpos = dir.pathRel.lastIndexOf("/");
            dir.nameLoc = dir.pathRel.substring(rpos + 1);
            rels.add(dir);
        }
        //子目录
        else {
            // /a/b/c/d/e=>,a,b,c,d,e
            int pos = 0;
            while ( (pos = pathRel.indexOf("/", pos)) !=-1)
            {
                FileInf dir = new FileInf();
                dir.pathRel = pathRel.substring(0, pos);
                dir.nameLoc = PathTool.getName(dir.pathRel);
                if (StringUtils.isEmpty(dir.nameLoc)) dir.nameLoc = "根目录";
                if (StringUtils.isEmpty(dir.pathRel)) dir.pathRel = "/";
                rels.add(dir);
                pos++;
            }
            FileInf f = new FileInf();
            f.pathRel = pathRel;
            f.nameLoc = PathTool.getName(f.pathRel);
            rels.add(f);
        }
        return JSONArray.fromObject(rels);
    }
	
	public FileInf read(String id) throws ParseException, IllegalAccessException, SQLException {
	    return SqlTable.build("up6_folders").readOne(FileInf.build(),
                SqlWhere.build().eq("f_id",id));
    }
	
	/**
	 * 取同名目录信息
	 * @param pathRel
	 * @param id
	 * @return
	 */
	public FileInf read(String pathRel, String id) throws ParseException, IllegalAccessException, SQLException {
        return SqlTable.build("up6_folders").readOne(FileInf.build(),
                SqlWhere.build().eq("f_pathRel",pathRel)
                        .eq("f_deleted",false)
                        .ineq("f_id",id));
    }

    public void complete(String id) throws ParseException, IllegalAccessException, SQLException {
        SqlTable.build("up6_folders").update(
                SqlSeter.build().set("f_complete",true),
                SqlWhere.build().eq("f_id",id)
        );
    }

	public Boolean exist_same_file(String name,String pid)
    {
        SqlWhereMerge swm = new SqlWhereMerge();
        swm.equal("f_nameLoc", name.trim());
        swm.equal("f_pid", pid.trim());
        swm.equal("f_deleted", 0);

        String sql = String.format("select f_id from up6_files where %s ", swm.to_sql());

        SqlExec se = new SqlExec();
        JSONArray arr = se.exec("up6_files", sql, "f_id", "");
        return arr.size() > 0;
    }
	
	/**
	 * 检查是否存在同名目录
	 * @param pathRel
	 * @return
	 */
	public Boolean exist_same_folder(String pathRel)
    {
        SqlWhereMerge swm = new SqlWhereMerge();
        swm.equal("f_pathRel", pathRel);
        swm.equal("f_deleted", 0);
        String where = swm.to_sql();

        String sql = String.format("(select f_id from up6_files where %s ) union (select f_id from up6_folders where %s)", where,where);

        SqlExec se = new SqlExec();
        JSONArray fid = se.exec("up6_files", sql, "f_id", "");
        return fid.size() > 0;
	}
	
    public Boolean rename_file_check(String newName,String pid)
    {
        SqlExec se = new SqlExec();            
        JSONArray res = se.select("up6_files"
            , "f_id"
            ,new SqlParam[] {
                new SqlParam("f_nameLoc",newName)
                ,new SqlParam("f_pid",pid)
            },"");
        return res.size() > 0;
    }
    
    public Boolean rename_folder_check(String newName, String pid)
    {
        SqlExec se = new SqlExec();
        JSONArray res = se.select("up6_folders"
            , "f_id"
            , new SqlParam[] {
                new SqlParam("f_nameLoc",newName)
                ,new SqlParam("f_pid",pid)
            },"");
        return res.size() > 0;
    }

    public void rename_file(String name,String id) {
        SqlExec se = new SqlExec();
        se.update("up6_files"
            , new SqlParam[] { new SqlParam("f_nameLoc", name) }
            , new SqlParam[] { new SqlParam("f_id", id) });
    }
    
    public void rename_folder(String name, String id, String pid) {
        SqlExec se = new SqlExec();
        se.update("up6_folders"
            , new SqlParam[] { new SqlParam("f_nameLoc", name) }
            , new SqlParam[] { new SqlParam("f_id", id) });
    }
    
    public void del(String id,int uid) throws ParseException, IllegalAccessException, SQLException {
        SqlTable.build("up6_folders").update(
                SqlSeter.build().set("f_deleted",true),
                SqlWhere.build()
                        .eq("f_id",id)
                        .eq("f_uid",uid)
        );
    }

	public boolean existSameFolder(String name,String pid)
	{
		SqlExec se = new SqlExec();
		
		//子目录
		if(!StringUtils.isEmpty(pid))
		{
			return se.count("up6_folders",new SqlParam[] {
					new SqlParam("f_nameLoc",name),
					new SqlParam("f_pid",pid),
					new SqlParam("f_deleted",false)
			})>0;
		}//根目录
		else
		{
			return se.count("up6_files",new SqlParam[] {
					new SqlParam("f_nameLoc",name),
					new SqlParam("f_pid",pid),
					new SqlParam("f_deleted",false)
			})>0;			
		}
	}	


	/**
	 * 更新子文件路径
	 * @param pathRelOld
	 * @param pathRelNew
	 */
	public void updatePathRel(String pathRelOld,String pathRelNew)
	{
        //更新子文件路径
        String sql = String.format("update up6_folders set f_pathRel=REPLACE(f_pathRel,'%s/','%s/') where CHARINDEX('%s/',f_pathRel)>0",
            pathRelOld,
            pathRelNew,
            pathRelOld
            );
        
        SqlExec se = new SqlExec();
        se.exec(sql);		
	}

	public void add(FileInf f) throws ParseException, IllegalAccessException, SQLException {
        SqlTable.build("up6_folders").insert(f);
    }

    //批量添加
    public void addBatch(List<FileInf> arr) throws SQLException, ParseException, IllegalAccessException {
        SqlTable.build("up6_folders").inserts(arr);
    }
}
